const http = require('http');
const url = require('url');

// 模拟电影数据
const movies = [
    { id: 1, name: "肖申克的救赎", rating: 9.7 },
    { id: 2, name: "霸王别姬", rating: 9.6 },
    { id: 3, name: "阿甘正传", rating: 9.5 },
    { id: 4, name: "这个杀手不太冷", rating: 9.4 },
    { id: 5, name: "泰坦尼克号", rating: 9.4 }
];

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    
    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    if (parsedUrl.pathname === '/getlist' && req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(movies));
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

const PORT = 8081;
server.listen(PORT, () => {
    console.log(`电影数据API服务器运行在 http://localhost:${PORT}`);
    console.log(`数据接口: http://localhost:${PORT}/getlist`);
});